﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ClientSide
{
    #region Using

    using DevComponents.DotNetBar;
    using System.Net.Sockets;
    using System.Net;
    using System.Threading;

    #endregion

    public partial class FrmPlayGame : Office2007Form
    {
        #region variables

        /// <summary>
        /// Socket to receive and send data
        /// </summary>
        public AsyncSocket SocClient { get; set; }

        /// <summary>
        /// Name of player
        /// </summary>
        public string PlayerName { get; set; }

        /// <summary>
        /// Delegate to write log status
        /// </summary>
        /// <param name="data"></param>
        private delegate void UpdateScoreDel(string data);

        /// <summary>
        /// Delegate to write log status
        /// </summary>
        /// <param name="data"></param>
        private delegate void PlayAgainDel();

        private bool m_SentResult;
        #endregion

        public FrmPlayGame()
        {
            InitializeComponent();
        }

        /// <summary>
        /// When AsyncSocket object raises event handler, this routine will be called
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleSocketEvent(object sender, EventArgs e)
        {
            var dataTransfer = (SocketEvent)e;
            var compData = dataTransfer.Data.Split(new char[] { ':' });
            switch (compData[0])
            {
                case "ERROR":
                    MessageBox.Show(compData[1], "Error", MessageBoxButtons.OK);
                    break;

                case "RESULTSET":
                    timer1.Enabled = false;
                    var compResult = compData[1].Split(new char[] { '#' });
                    if (compResult[0] == "1")
                    {
                        this.UpdateScore(compResult[1]);
                    }
                    this.PlayAgain();
                    UpdateOpponentResult(compResult[2]);
                    UpdateStatusResult(compResult[0]);
                    break;
            }
        }

        /// <summary>
        /// Update opponent result
        /// </summary>
        private void UpdateStatusResult(string result)
        {
            if (ptbResult.InvokeRequired)
            {
                UpdateScoreDel del = new UpdateScoreDel(UpdateStatusResult);
                ptbResult.Invoke(del, new object[] { result });
                return;
            }
            switch (result)
            {
                case "1":
                    ptbResult.BackgroundImage = imglstStatus.Images["win"];
                    break;

                case "0":
                    ptbResult.BackgroundImage = imglstStatus.Images["draw"];
                    break;

                case "-1":
                    ptbResult.BackgroundImage = imglstStatus.Images["lose"];
                    break;
            }
        }

        /// <summary>
        /// Update opponent result
        /// </summary>
        private void UpdateOpponentResult(string result)
        {
            if (ptbOpponent.InvokeRequired)
            {
                UpdateScoreDel del = new UpdateScoreDel(UpdateOpponentResult);
                ptbOpponent.Invoke(del, new object[] { result });
                return;
            }
            switch (result)
            {
                case "ROCK":
                    ptbOpponent.BackgroundImage = imglstItem.Images["bua"];
                    break;

                case "PAPER":
                    ptbOpponent.BackgroundImage = imglstItem.Images["bao"];
                    break;

                case "SCISSORS":
                    ptbOpponent.BackgroundImage = imglstItem.Images["keo"];
                    break;
            }
        }

        /// <summary>
        /// Write log status
        /// </summary>
        /// <param name="data"></param>
        private void UpdateScore(string score)
        {
            if (lblScore.InvokeRequired)
            {
                UpdateScoreDel del = new UpdateScoreDel(UpdateScore);
                lblScore.Invoke(del, new object[] { score });
                return;
            }
            lblScore.Text = score;
        }

        /// <summary>
        /// Play again
        /// </summary>
        /// <param name="data"></param>
        private void PlayAgain()
        {
            if (btnPlayAgain.InvokeRequired)
            {
                PlayAgainDel del = new PlayAgainDel(PlayAgain);
                lblScore.Invoke(del, new object[] { });
                return;
            }
            btnPlayAgain.Enabled = true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PlayGame_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void FrmPlayGame_Load(object sender, EventArgs e)
        {
            //Add handlers for shortcut Panel controls MouseEnter event
            ptbRock.MouseEnter += new EventHandler(NavigationPanel_MouseEnter);
            ptbPaper.MouseEnter += new EventHandler(NavigationPanel_MouseEnter);
            ptbScissors.MouseEnter += new EventHandler(NavigationPanel_MouseEnter);

            //Add handlers for shortcut Panel controls MouseLeave event
            ptbRock.MouseLeave += new EventHandler(NavigationPanel_MouseLeave);
            ptbPaper.MouseLeave += new EventHandler(NavigationPanel_MouseLeave);
            ptbScissors.MouseLeave += new EventHandler(NavigationPanel_MouseLeave);

            //'Add handlers for shortcut Label controls MouseUp event
            ptbRock.MouseUp += new MouseEventHandler(NavigationPanel_MouseUp);
            ptbPaper.MouseUp += new MouseEventHandler(NavigationPanel_MouseUp);
            ptbScissors.MouseUp += new MouseEventHandler(NavigationPanel_MouseUp);

            lblPlayerName.Text = this.PlayerName;
            lblNumSet.Text = "0";
            lblScore.Text = "0";
            timer1.Enabled = true;
            this.btnPlayAgain.Enabled = false;
            this.m_SentResult = false;

            this.SocClient.PlayingHandler += HandleSocketEvent;
        }

        /// <summary>
        /// Occurs when the mouse pointer enters the control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NavigationPanel_MouseEnter(Object sender, EventArgs e)
        {
            ((PictureBox)sender).Cursor = Cursors.Hand;
        }

        /// <summary>
        /// Occurs when the mouse pointer leaves the control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NavigationPanel_MouseLeave(Object sender, EventArgs e)
        {
            ((PictureBox)sender).Cursor = Cursors.Default;
        }

        /// <summary>
        /// Occurs when the mouse pointer is over the control and a mouse button is released.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NavigationPanel_MouseUp(Object sender, MouseEventArgs e)
        {
            if (btnPlayAgain.Enabled || this.m_SentResult)
            {
                return;
            }
            var resultStr = string.Empty;
            if (((PictureBox)sender).Name == "ptbRock")
            {
                ptbYou.BackgroundImage = imglstItem.Images["bua"];
                resultStr = "ROCK";
            }
            else if (((PictureBox)sender).Name == "ptbPaper")
            {
                ptbYou.BackgroundImage = imglstItem.Images["bao"];
                resultStr = "PAPER";
            }
            else if (((PictureBox)sender).Name == "ptbScissors")
            {
                ptbYou.BackgroundImage = imglstItem.Images["keo"];
                resultStr = "SCISSORS";
            }

            this.m_SentResult = true;
            lblNumSet.Text = (int.Parse(lblNumSet.Text) + 1).ToString();
            this.SocClient.SendPlayingResult(this.PlayerName, resultStr);
        }

        private int DeplayChangeImg = 1;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (DeplayChangeImg == 1)
            {
                ptbOpponent.BackgroundImage = imglstItem.Images["keo"];
            }
            else if (DeplayChangeImg == 2)
            {
                ptbOpponent.BackgroundImage = imglstItem.Images["bua"];
            }
            else if (DeplayChangeImg == 3)
            {
                ptbOpponent.BackgroundImage = imglstItem.Images["bao"];
            }

            if (DeplayChangeImg > 3)
            {
                ptbOpponent.BackgroundImage = imglstItem.Images["keo"];
                DeplayChangeImg = 1;
            }
            DeplayChangeImg++;
        }

        private void btnPlayAgain_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            ptbYou.BackgroundImage = null;
            ptbResult.BackgroundImage = null;
            btnPlayAgain.Enabled = false;
            this.m_SentResult = false;
        }
    }
}
